package com.java.basis.thread.n3.jiaoti;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangning
 * @create 2022-01-25 11:02
 */
@Slf4j(topic = "c.Test02")
public class Test02 {
	public static void main(String[] args) throws InterruptedException {
		AwaitSignal awaitSignal = new AwaitSignal(5);
		//给每一个线程创建一个休息室
		Condition a = awaitSignal.newCondition();
		Condition b = awaitSignal.newCondition();
		Condition c = awaitSignal.newCondition();
		new Thread(() -> {
			awaitSignal.print("a", a, b);
		}).start();
		new Thread(() -> {
			awaitSignal.print("b", b, c);
		}).start();
		new Thread(() -> {
			awaitSignal.print("c", c, a);
		}).start();
		Thread.sleep(1000);
		//主线程去唤醒a休息室，否则会都在等待中
		awaitSignal.lock();
		try {
			a.signal();
		} finally {
			awaitSignal.unlock();
		}
	}
}

class AwaitSignal extends ReentrantLock {
	//循环次数
	private int loopNumber;

	public AwaitSignal(int loopNumber) {
		this.loopNumber = loopNumber;
	}

	//参数1：打印内容，参数2：进入哪一间休息室等待

	public void print(String str, Condition current, Condition next) {
		for (int i = 0; i < loopNumber; i++) {
			lock();
			try {
				current.await();
				System.out.print(str);
				next.signal();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				unlock();
			}
		}
	}
}

